package com.ruoyi.wifiauth.service.impl;

import java.util.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.ruoyi.wifiauth.mapper.WifiAuthMonitorMapper;
import com.ruoyi.wifiauth.service.IWifiAuthMonitorService;

/**
 * WiFi认证监控服务实现
 * 
 * @author ruoyi
 */
@Service
public class WifiAuthMonitorServiceImpl implements IWifiAuthMonitorService {
    
    @Autowired
    private WifiAuthMonitorMapper monitorMapper;

    @Override
    public Map<String, Object> getAuthOverview(String startDate, String endDate) {
        Map<String, Object> params = buildParams(startDate, endDate);
        Map<String, Object> data = monitorMapper.getAuthOverview(params);
        
        Map<String, Object> result = new HashMap<>();
        result.put("totalAuths", getLongValue(data, "totalAuths"));
        result.put("successAuths", getLongValue(data, "successAuths"));
        result.put("failedAuths", getLongValue(data, "failedAuths"));
        result.put("successRate", getDoubleValue(data, "successRate"));
        result.put("avgAuthTime", getDoubleValue(data, "avgAuthTime"));
        result.put("uniqueUsers", getLongValue(data, "uniqueUsers"));
        
        return result;
    }

    @Override
    public Map<String, Object> getAuthTrendData(String startDate, String endDate, String deviceId) {
        Map<String, Object> params = buildParams(startDate, endDate);
        if (StringUtils.hasText(deviceId)) {
            params.put("deviceId", deviceId);
        }
        
        List<Map<String, Object>> data = monitorMapper.getAuthTrendData(params);
        
        Map<String, Object> result = new HashMap<>();
        List<String> dates = new ArrayList<>();
        List<Long> totalAuths = new ArrayList<>();
        List<Long> successAuths = new ArrayList<>();
        List<Long> failedAuths = new ArrayList<>();
        
        for (Map<String, Object> item : data) {
            dates.add(getString(item, "date"));
            totalAuths.add(getLongValue(item, "totalAuths"));
            successAuths.add(getLongValue(item, "successAuths"));
            failedAuths.add(getLongValue(item, "failedAuths"));
        }
        
        result.put("dates", dates);
        result.put("totalAuths", totalAuths);
        result.put("successAuths", successAuths);
        result.put("failedAuths", failedAuths);
        
        return result;
    }

    @Override
    public Map<String, Object> getAuthSuccessRate(String startDate, String endDate) {
        Map<String, Object> params = buildParams(startDate, endDate);
        List<Map<String, Object>> data = monitorMapper.getAuthSuccessRate(params);
        
        Map<String, Object> result = new HashMap<>();
        List<String> devices = new ArrayList<>();
        List<Double> successRates = new ArrayList<>();
        List<Long> authCounts = new ArrayList<>();
        
        for (Map<String, Object> item : data) {
            devices.add(getString(item, "deviceName"));
            successRates.add(getDoubleValue(item, "successRate"));
            authCounts.add(getLongValue(item, "authCount"));
        }
        
        result.put("devices", devices);
        result.put("successRates", successRates);
        result.put("authCounts", authCounts);
        
        return result;
    }

    @Override
    public Map<String, Object> getAuthTimeAnalysis(String startDate, String endDate) {
        Map<String, Object> params = buildParams(startDate, endDate);
        List<Map<String, Object>> data = monitorMapper.getAuthTimeAnalysis(params);
        
        Map<String, Object> result = new HashMap<>();
        List<String> devices = new ArrayList<>();
        List<Double> avgTimes = new ArrayList<>();
        List<Long> maxTimes = new ArrayList<>();
        List<Long> minTimes = new ArrayList<>();
        
        for (Map<String, Object> item : data) {
            devices.add(getString(item, "deviceName"));
            avgTimes.add(getDoubleValue(item, "avgTime"));
            maxTimes.add(getLongValue(item, "maxTime"));
            minTimes.add(getLongValue(item, "minTime"));
        }
        
        result.put("devices", devices);
        result.put("avgTimes", avgTimes);
        result.put("maxTimes", maxTimes);
        result.put("minTimes", minTimes);
        
        return result;
    }

    @Override
    public Map<String, Object> getFailureReasonDistribution(String startDate, String endDate) {
        Map<String, Object> params = buildParams(startDate, endDate);
        List<Map<String, Object>> data = monitorMapper.getFailureReasonDistribution(params);
        
        Map<String, Object> result = new HashMap<>();
        List<String> reasons = new ArrayList<>();
        List<Long> counts = new ArrayList<>();
        List<String> devices = new ArrayList<>();
        
        for (Map<String, Object> item : data) {
            reasons.add(getString(item, "failureReason"));
            counts.add(getLongValue(item, "count"));
            devices.add(getString(item, "deviceName"));
        }
        
        result.put("reasons", reasons);
        result.put("counts", counts);
        result.put("devices", devices);
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getDeviceAuthRank(String startDate, String endDate, Integer limit) {
        Map<String, Object> params = buildParams(startDate, endDate);
        if (limit != null) {
            params.put("limit", limit);
        }
        
        return monitorMapper.getDeviceAuthRank(params);
    }

    @Override
    public Map<String, Object> getUserBehaviorAnalysis(String startDate, String endDate) {
        Map<String, Object> params = buildParams(startDate, endDate);
        List<Map<String, Object>> data = monitorMapper.getUserBehaviorAnalysis(params);
        
        Map<String, Object> result = new HashMap<>();
        List<String> userGroups = new ArrayList<>();
        List<Long> userCounts = new ArrayList<>();
        List<Double> avgAuthTimes = new ArrayList<>();
        
        for (Map<String, Object> item : data) {
            userGroups.add(getString(item, "authCountGroup"));
            userCounts.add(getLongValue(item, "userCount"));
            avgAuthTimes.add(getDoubleValue(item, "avgAuthTime"));
        }
        
        result.put("userGroups", userGroups);
        result.put("userCounts", userCounts);
        result.put("avgAuthTimes", avgAuthTimes);
        
        return result;
    }

    @Override
    public int recordAuthProcess(String sessionId, String deviceId, String openid, Integer authStatus, Long authTime, String failureReason) {
        Map<String, Object> params = new HashMap<>();
        params.put("sessionId", sessionId);
        params.put("deviceId", deviceId);
        params.put("openid", openid);
        params.put("status", authStatus); // 修改为status字段
        params.put("authDuration", authTime); // 修改为authDuration字段
        params.put("errorMsg", failureReason); // 修改为errorMsg字段
        // 可以根据需要添加其他字段
        params.put("userIp", null); // 用户IP，可从其他地方获取
        params.put("adViewed", 0); // 是否观看广告，默认0
        
        return monitorMapper.recordAuthProcess(params);
    }

    @Override
    public Map<String, Object> getRealTimeAuthStatus() {
        List<Map<String, Object>> data = monitorMapper.getRealTimeAuthStatus();
        
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> realTimeStatus = new ArrayList<>();
        
        for (Map<String, Object> item : data) {
            Map<String, Object> statusItem = new HashMap<>();
            statusItem.put("deviceName", getString(item, "deviceName"));
            statusItem.put("authCount", getLongValue(item, "authCount"));
            statusItem.put("successRate", getDoubleValue(item, "successRate"));
            statusItem.put("status", getAuthStatus(getDoubleValue(item, "successRate")));
            realTimeStatus.add(statusItem);
        }
        
        result.put("realTimeStatus", realTimeStatus);
        return result;
    }

    private Map<String, Object> buildParams(String startDate, String endDate) {
        Map<String, Object> params = new HashMap<>();
        if (StringUtils.hasText(startDate)) {
            params.put("startDate", startDate);
        }
        if (StringUtils.hasText(endDate)) {
            params.put("endDate", endDate);
        }
        return params;
    }

    private String getAuthStatus(Double successRate) {
        if (successRate >= 90.0) {
            return "优秀";
        } else if (successRate >= 70.0) {
            return "良好";
        } else if (successRate >= 50.0) {
            return "一般";
        } else {
            return "需优化";
        }
    }

    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return 0L;
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        try {
            return Long.valueOf(value.toString());
        } catch (NumberFormatException e) {
            return 0L;
        }
    }

    private Double getDoubleValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return 0.0;
        if (value instanceof Number) {
            return ((Number) value).doubleValue();
        }
        try {
            return Double.valueOf(value.toString());
        } catch (NumberFormatException e) {
            return 0.0;
        }
    }

    private String getString(Map<String, Object> map, String key) {
        Object value = map.get(key);
        return value == null ? "" : value.toString();
    }
}